<template>
  <div class="favorites-container">
    <h2  style="text-align: center;">我的收藏</h2>

    <!-- 搜索陪诊员 -->
    <div class="search-box">
      <div class="search-input-wrapper">
        <el-input v-model="searchKeyword" placeholder="输入陪诊员Id进行搜索" class="short-input" />
        <el-button type="primary" @click="searchEscorts">搜索</el-button>
      </div>
    </div>

    <!-- 搜索结果 -->
    <div v-if="searching" class="search-result">
      <p>正在搜索...</p>
    </div>

    <!-- 搜索结果 -->
    <div v-else-if="searchResults.length > 0" class="search-result">
      <h4 style="text-align: center;">搜索到的陪诊员：</h4>
      <div class="escort-list">
        <div v-for="escort in searchResults" :key="escort.id" class="escort-card">
          <p><strong>ID:</strong> {{ escort.id }}</p>
          <p><strong>姓名:</strong> {{ escort.realName }}</p>
          <p><strong>手机号:</strong> {{ escort.phone }}</p>
          <p><strong>性别:</strong> {{ escort.gender }}</p>
          <p><strong>年龄:</strong> {{ escort.age }}</p>
          <p><strong>服务次数:</strong> {{ escort.serviceCount }}</p>
          <p><strong>个人简介:</strong> {{ escort.profile }}</p>
<!--          <el-button
              type="success"
              size="small"
              :disabled="escort.isFavorited"
              @click="addToFavorites(escort)"
          >
            <el-icon name="favorite">
              <component :is="escort.isFavorited ? HeartFilled : Heart" />
            </el-icon>
            {{ escort.isFavorited ? '已收藏' : '收藏' }}
          </el-button>-->
        </div>
      </div>
    </div>


    <div v-else-if="searchKeyword && !searchResults.length" class="search-result">
      <p>未找到相关陪诊员</p>
    </div>

    <!-- 收藏统计 -->
    <div class="favorite-count">
      当前共收藏了 {{ favorites.length }} 个陪诊员
    </div>

    <!-- 排序选项 -->
    <div class="sort-options">
      <label for="sortBy">排序方式：</label>
      <el-select v-model="sortBy" id="sortBy" @change="fetchFavorites">
        <el-option label="最新收藏" value="desc" />
        <el-option label="最早收藏" value="asc" />
      </el-select>
    </div>
    <div v-for="escort in searchResults" :key="escort.id" class="escort-card">
      <!-- 原有内容... -->
      <el-button
          type="primary"
          size="small"
          @click="prepareAppointment(escort)"
      >
        预约此陪诊员
      </el-button>
    </div>

    <!-- 收藏列表 -->
    <el-table :data="favorites" style="width: 100%" border>
      <el-table-column prop="escortId" label="陪诊员ID" />
      <el-table-column prop="escortName" label="陪诊员姓名" />
      <el-table-column prop="createTime" label="收藏时间" width="160" />
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" type="danger" @click="removeFavorite(scope.row)">取消收藏</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        layout="prev, pager, next"
        :total="total"
        v-model:current-page="currentPage"
        :page-size="pageSize"
        @current-change="fetchFavorites"
        style="margin-top: 20px"
    />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import qs from 'qs'
import { ElMessage, ElMessageBox } from 'element-plus'


const BASE_URL = 'http://localhost:8080'

// 数据模型
const favorites = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 排序字段
const sortBy = ref('desc') // desc: 最新，asc: 最早

const searchKeyword = ref('')
const searching = ref(false)
const searchResults = ref([])

// 获取收藏列表
const fetchFavorites = async () => {
  try {
    let params = {
      page: currentPage.value,
      size: pageSize.value,
      sort: sortBy.value
    }
    let data = qs.stringify(params)
    const res = await axios.get(BASE_URL + '/v1/user/favorites/list?' + data)
    if (res.data.state === 2000) {
      favorites.value = res.data.data || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.data.msg)
    }
  } catch (error) {
    console.error('获取收藏失败:', error)
    ElMessage.error('获取收藏列表失败')
  }
}

// 取消收藏
const removeFavorite = async (row) => {
  try {
    await ElMessageBox.confirm('确定要取消该收藏吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const res = await axios.delete(BASE_URL + `/v1/user/favorites/cancel/${row.escortId}`)
    if (res.data.state === 2000) {
      ElMessage.success('取消收藏成功')
      fetchFavorites() // 刷新列表
    } else {
      ElMessage.error(res.data.msg)
    }
  } catch (error) {
    console.error('取消收藏失败:', error)
    ElMessage.error(error.response?.data?.message || '取消收藏失败')
  }
}

// 搜索陪诊员
const searchEscorts = async () => {
  if (!searchKeyword.value.trim()) {
    searchResults.value = []
    return
  }

  searching.value = true
  try {
    let params = {
      keyword: searchKeyword.value,
      page: 1,
      size: 5
    }
    let data = qs.stringify(params)
    const res = await axios.get(BASE_URL + '/v1/user/favorites/search-escort?' + data)
    if (res.data.state === 2000) {
      const escorts = res.data.data || []

      // 查询每个陪诊员是否已收藏
      const results = await Promise.all(
          escorts.map(async (escort) => {
            const checkRes = await axios.get(BASE_URL + `/v1/user/favorites/check/${escort.id}`)
            return {
              ...escort,
              isFavorited: checkRes.data.data || false
            }
          })
      )

      searchResults.value = results
    } else {
      ElMessage.error(res.data.msg)
    }
  } catch (error) {
    console.error('搜索陪诊员失败:', error)
    ElMessage.error('搜索陪诊员失败')
  } finally {
    searching.value = false
  }
}

// 添加收藏
const addToFavorites = async (escort) => {
  try {
    const res = await axios.post(BASE_URL + '/v1/user/favorites/add', { escortId: escort.id })
    if (res.data.state === 2000) {
      ElMessage.success('收藏成功')
      escort.isFavorited = true // 更新状态
      fetchFavorites() // 刷新收藏列表
    } else {
      ElMessage.error(res.data.msg)
    }
  } catch (error) {
    console.error('添加收藏失败:', error)
    ElMessage.error('收藏失败，请重试')
  }
}
// 新增方法
const prepareAppointment = (escort) => {
  router.push({
    path: '/appointments',
    query: {
      escortId: escort.id,
      escortName: escort.realName
    }
  })
}


onMounted(() => {
  fetchFavorites()
})
</script>

<style scoped>


/*
.search-box {
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
}

.search-input-wrapper {
  display: flex;
  align-items: center;
  gap: 10px;
}

.short-input {
  width: 200px;
}

.favorite-count {
  margin-bottom: 15px;
  font-weight: bold;
  color: #4a90e2;
}

.sort-options {
  margin-bottom: 15px;
}

.escort-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: center; !* 水平居中 *!
  gap: 20px;
  padding: 0 10px;
}

!*.escort-card {
  background-color: #f9f9f9;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 15px;
  min-width: 200px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}*!
!* 主容器背景和字体颜色 *!
.favorites-container {
  padding: 30px;
  background-color: #fff8f0; !* 温暖米黄色 *!
  color: #4a4a4a;
  font-family: 'Segoe UI', sans-serif;
}

!* 搜索区域阴影增强 *!
.search-box .search-input-wrapper {
  box-shadow: 0 2px 10px rgba(255, 153, 153, 0.2);
  border-radius: 10px;
  padding: 10px;
  background: white;
}

!* 输入框圆角优化 *!
.short-input ::v-deep .el-input__inner {
  border-radius: 8px;
  border: 1px solid #ffcccc;
}

!* 搜索按钮渐变色 *!
.el-button--primary {
  background: linear-gradient(to right, #ff9999, #ff6699);
  border: none;
  transition: background 0.3s ease;
}

.el-button--primary:hover {
  background: linear-gradient(to right, #ff6699, #ff3399);
}

!* 收藏统计文字美化 *!
.favorite-count {
  font-size: 1.1rem;
  margin-bottom: 15px;
  font-weight: bold;
  color: #d9534f;
  text-align: center;
  letter-spacing: 1px;
}

!* 排序下拉选择框美化 *!
.sort-options label {
  font-weight: bold;
  color: #e67e7e;
  margin-right: 10px;
}

.sort-options .el-select {
  width: 150px;
}

!* 卡片式陪诊员信息展示 *!
.escort-card {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(255, 153, 153, 0.15);
  padding: 20px;
  min-width: 220px;
  transition: transform 0.2s;
  border: 1px solid #ffe6e6;
}

.escort-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 20px rgba(255, 153, 153, 0.3);
}

!* 分页样式微调 *!
.el-pagination {
  display: flex;
  justify-content: center;
  margin-top: 25px;
}
*/
/* 主容器背景和字体颜色 */
.favorites-container {
  padding: 30px;
  background-color:  #f0f8ff; /* 清新浅绿背景 */
  color: #2e2e2e;
  font-family: 'Segoe UI', sans-serif;
}

/* 搜索区域阴影增强 */
.search-box .search-input-wrapper {
  box-shadow: 0 2px 10px rgba(70, 130, 180, 0.2);
  border-radius: 10px;
  padding: 10px;
  background: white;
}

/* 输入框圆角优化 */
.short-input ::v-deep .el-input__inner {
  border-radius: 8px;
  border: 1px solid  #cce0ff;
}

/* 搜索按钮渐变色 */
.el-button--primary {
  background: linear-gradient(to right, #4a90e2, #6bc1ff);
  border: none;
  transition: background 0.3s ease;
}

.el-button--primary:hover {
  background: linear-gradient(to right, #6bc1ff, #3a90e2);
}

/* 收藏统计文字美化 */
.favorite-count {
  font-size: 1.1rem;
  margin-bottom: 15px;
  font-weight: bold;
  color: #1e3d59;
  text-align: center;
  letter-spacing: 1px;
}

/* 排序下拉选择框美化 */
.sort-options label {
  font-weight: bold;
  color: #6bbaff;
  margin-right: 10px;
}

.sort-options .el-select {
  width: 150px;
}

/* 卡片式陪诊员信息展示 */
.escort-card {
  background-color: white;
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(70, 130, 180, 0.15);
  padding: 20px;
  min-width: 220px;
  transition: transform 0.2s ease, box-shadow 0.3s ease;
  border: 1px solid #d0e0ff;
}

.escort-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 20px rgba(70, 130, 180, 0.3);
}

/* 分页样式微调 */
.el-pagination {
  display: flex;
  justify-content: center;
  margin-top: 25px;
}

/* 其他已有样式保持不变... */
.search-box {
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
}

.search-input-wrapper {
  display: flex;
  align-items: center;
  gap: 10px;
}

.short-input {
  width: 200px;
}

.escort-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 20px;
  padding: 0 10px;
}



</style>
